<template>
	<div class="myUpload">
		<div class="uploadSheet">
			<div class="uploadHead" v-show="title">{{title}}</div>
			<div class="uploadContent">
				<el-upload :action="HOST1 + url" :limit="limit" :multiple="true" ref='upload' :auto-upload="false"
					:list-type="listType" :http-request="uploadEvent" :on-change="uploadOnChange"
					:on-remove="uploadOnRemove">
					<i class="el-icon-plus"></i>
				</el-upload>
			</div>
		</div>
	</div>
</template>
<script>
	import axios from 'axios'
	import lrz from "lrz"
	import {
		base64encode,
		base64decode,
		querystringify
	} from '@/utils/base64'
	export default {
		name: 'uploader',
		data() {
			return {
				uploadParams: '',
                fileList: [],
                originFileList: [] // 上传的源文件
			}
		},
		props: {
			title: {
				type: String,
				default: ''
			},
			url: {
				type: String,
				default: ''
			},
			listType: {
				type: String,
				default: 'picture-card'
			},
			// 存放图片数组的字段
			name: {
				type: String,
				default: 'file'
			},
			// 除了图片 额外的参数
			params: {
				type: Object,
				default: () => {}
			},
			limit: {
				type: Number,
				default: 1
			},
			// 请求之后是否提示消息，如果有同时提交两个上传图片的组件，消息就会提示两遍
			isNotice: {
				type: Boolean,
				default: true
			},
			// 上传完成后，是否清除图片
			isClearFiles: {
				type: Boolean,
				default: true
            },
            // 是否压缩
            compress: {
                type: Boolean,
                default: true
            }
		},
		methods: {
			// 选择上传文件发生变化是触发
			uploadOnChange(val, fileList) {
				this.$emit('onChange', val, fileList)
				this.fileList = fileList.slice(0)
				// const isJPG = val.raw.type === 'image/jpeg';
				// const isPNG = val.raw.type === 'image/png';
				// const isLt2M = val.size / 1024 / 1024 < 10;
				// if (!isJPG && !isPNG) {
				// 	this.$alert("上传图片只能是 JPG.PNG 格式!", '提示', {
				// 		confirmButtonText: '确定'
				// 	})
				// 	this.clearFiles()
				// }
				// if (!isLt2M) {
				// 	this.$alert("上传图片大小不能超过 10MB!", '提示', {
				// 		confirmButtonText: '确定'
				// 	})
				// 	this.clearFiles()
				// }
			},
			uploadOnRemove(val, fileList) {
				this.$emit('onRemove', val, fileList)
				this.fileList = fileList.slice(0)
			},
			// 覆盖默认的上传行为，可以自定义上传的实现
			uploadEvent(file) {
                if (this.compress) {
                    this.originFileList.push(file.file)
                } else {
                    this.uploadParams.append(this.name, file.file)
                }
			},
			// 提交图片
			async submit(parentThis, loopParams) {
				let that = this
				parentThis.$emit('isLoading', true, "拼命加载中");
				let params = loopParams
				this.uploadParams = new FormData()
                this.$refs.upload.submit();
				// this.uploadParams.append('param', base64encode(JSON.stringify({
				// 	entity: {
				// 		...params
				// 	}
                // })))
				this.uploadParams.append('params',  JSON.stringify(params))
				let config = {
					headers: {
						'Content-Type': 'multipart/form-data',
						Authorization: `Bearer${localStorage.getItem('jwt')}`,
						'cy-token': localStorage.getItem('jwt')
					}
				}
				try {
					if (this.compress) {
						for(let file of this.originFileList) {
							let b = await new Promise((resolve, reject) => {
								try {
									lrz(file).then(function (rst) {
										let blob = that.dataURLtoFile(rst.base64, rst.file.type);
										let fileOfBlob = new File([blob], rst.origin.name, {
											type: rst.file.type
										});
										resolve(fileOfBlob)
									}).catch(function (error) {
										reject(false)
									})
								} catch (eer) {
									reject(false)
								}
							})
							if (b !== false) {
								this.uploadParams.append(that.name, b)
							}
						}
					}
				}
				catch(err) {}
				return new Promise((resolve, reject) => {
					axios.post(this.HOST1 + this.url, this.uploadParams, config).then((res) => {
						let result = res.data
						parentThis.$emit('isLoading', false);
						let code = result.code
						if (code == 200) {
							if (this.isNotice) {
								this.$message({
									message: '保存成功',
									type: 'success'
								});
								this.$emit('onSuccess')
							}
                            this.isClearFiles ? this.clearFiles() : '';
                            this.uploadParams = {}
                            this.originFileList = []
							resolve(result);
						} else {
							if (this.isNotice) {
								this.$alert(result.message, '提示', {
									confirmButtonText: '确定',
									callback: action => {}
								})
							}
							reject(result)
						}
					}).catch((err) => {
						this.clearFiles()
						if (this.isNotice) {
							this.$alert("请求失败!", '提示', {
								confirmButtonText: '确定'
							})
						}
						parentThis.$emit('isLoading', false);
						reject(err)
					})
				})
			},
			// 清除图片
			clearFiles() {
				this.fileList = []
				this.$refs.upload ? this.$refs.upload.clearFiles() : '';
			},
			getImgNum() {
				return this.fileList.length
			},
			//将base64转换为blob
			dataURLtoFile(dataURI, type) {
				let binary = atob(dataURI.split(',')[1]);
				let array = [];
				for (let i = 0; i < binary.length; i++) {
					array.push(binary.charCodeAt(i));
				}
				return new Blob([new Uint8Array(array)], {
					type: type
				});
			}
		}
	}

</script>
<style lang="less">
	.myUpload {
		font-size: 28/50rem;
		display: block;
		padding-bottom: 50/50rem;

		.uploadSheet {
			>div {
				float: static;
				margin-bottom: 10/50rem;
			}

			&:after {
				content: '';
				clear: both;
			}

			.el-upload-list.el-upload-list--picture-card {
				.el-upload-list__item {
					width: 3.8rem;
					height: 3.8rem;
				}
			}

			.el-upload.el-upload--picture-card {
				width: 3.8rem;
				height: 3.8rem;
				line-height: 3.8rem;

				i.el-icon-plus {
					line-height: 3.8rem;
				}
			}
		}
	}

</style>
